package com.sc.thread.bingfabiancheng;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by Shen Chao on 2018-06-12-012.
 * <p>
 * CountDownLatch类位于java.util.concurrent包下，利用它可以实现类似计数器的功能。
 * 比如有一个任务A，它要等待其他4个任务执行完毕之后才能执行，此时就可以利用CountDownLatch来实现这种功能了。
 *
 * //调用await()方法的线程会被挂起，它会等待直到count值为0才继续执行
 * public void await() throws InterruptedException { };
 * //和await()类似，只不过等待一定的时间后count值还没变为0的话就会继续执行
 * public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };
 * //将count值减1
 * public void countDown() { };
 */
public class CountDownLatchTest {
    public static void main(String[] args) {
//        public CountDownLatch(int count) {  };  //参数count为计数值
        CountDownLatch countDownLatch = new CountDownLatch(2);

        new Thread(() -> {
            try {
                System.out.println("子线程：" + Thread.currentThread().getName() + "正在执行");
                Thread.sleep(2000);
                System.out.println("子线程：" + Thread.currentThread().getName() + "执行完毕");
                //将count值减1
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }) {
        }.start();

        new Thread(() -> {
            try {
                System.out.println("子线程: " + Thread.currentThread().getName() + "正在执行");
                Thread.sleep(2000);
                System.out.println("子线程: " + Thread.currentThread().getName() + "执行完毕");
                //将count值减1
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        try {
            System.out.println("等待两个线程执行完毕");
            //await()会使线程挂起，直到count为0才继续执行
            //            countDownLatch.await();
            //等待一定时间，count还没为0，继续执行
            countDownLatch.await(1000, TimeUnit.MILLISECONDS);
            System.out.println("两个线程执行完毕");
            System.out.println("继续执行主线程");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
